<template>
  <div class="student-detail-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-button icon="el-icon-arrow-left" @click="backHandler" class="back-btn">
        返回
      </el-button>
      <h2 class="page-title">学生详情</h2>
    </div>

    <!-- 加载状态 -->
    <el-loading v-if="loading" fullscreen text="加载中，请稍候..."></el-loading>

    <!-- 学生基本信息卡片 -->
    <el-card class="student-card" v-if="student && !loading">
      <!-- 基本信息区域 -->
      <div class="student-info">
        <h3 class="section-title">
          <i class="el-icon-user"></i> 基本信息
          <div>
            <el-button v-if="!isEditing" type="primary" icon="el-icon-edit" size="mini" @click="toggleEditMode">
              编辑
            </el-button>
            <el-button v-if="isEditing" type="success" icon="el-icon-check" size="mini" @click="saveEdit"
              style="margin-right: 8px;">
              保存
            </el-button>
            <el-button v-if="isEditing" type="info" icon="el-icon-refresh" size="mini" @click="toggleEditMode">
              取消
            </el-button>
          </div>
        </h3>

        <el-row :gutter="20" class="info-row">
          <el-col :span="6">
            <span class="info-label">姓名：</span>
            <template v-if="isEditing">
              <el-input v-model="editForm.name" size="mini" class="info-input"></el-input>
            </template>
            <template v-else>{{ student.name }}</template>
          </el-col>
          <el-col :span="6">
            <span class="info-label">年龄：</span>
            <template v-if="isEditing">
              <el-input v-model.number="editForm.age" size="mini" type="number" class="info-input"></el-input>
            </template>
            <template v-else>{{ student.age }}</template>
          </el-col>
          <el-col :span="6">
            <span class="info-label">性别：</span>
            <template v-if="isEditing">
              <el-select v-model="editForm.gender" size="mini" class="info-select">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </template>
            <template v-else>{{ student.gender }}</template>
          </el-col>
          <el-col :span="6">
            <span class="info-label">专业：</span>
            <template v-if="isEditing">
              <el-input v-model="editForm.major" size="mini" class="info-input"></el-input>
            </template>
            <template v-else>{{ student.major }}</template>
          </el-col>
        </el-row>
      </div>

      <!-- 成绩信息 -->
      <div class="score-info" v-if="student.scores && Object.keys(student.scores).length">
        <h3 class="section-title">
          <i class="el-icon-book"></i> 课程成绩
        </h3>
        <el-table :data="scoreList" border stripe class="score-table" size="mini">
          <el-table-column prop="subject" label="科目" width="180" align="center"></el-table-column>
          <el-table-column prop="score" label="分数" width="100" align="center">
            <template slot-scope="scope">
              <template v-if="isEditing">
                <el-input v-model.number="scoreList[scope.$index].score" size="mini" type="number" min="0" max="100"
                  @input="handleScoreInput(scope.$index)"></el-input>
              </template>
              <template v-else>{{ scope.row.score }}</template>
            </template>
          </el-table-column>
          <el-table-column prop="grade" label="等级" width="100" align="center"></el-table-column>
          <el-table-column prop="status" label="状态" width="120" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.score >= 60 ? 'success' : 'danger'" size="mini">
                {{ scope.row.score >= 60 ? '通过' : '未通过' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <!-- 成绩统计 -->
        <div class="score-stats">
          <el-statistic title="平均分" :value="averageScore" :precision="1" class="stat-item" size="mini"></el-statistic>
          <el-statistic title="最高分" :value="maxScore" class="stat-item" size="mini"></el-statistic>
          <el-statistic title="最低分" :value="minScore" class="stat-item" size="mini"></el-statistic>
          <el-statistic title="及格率" :value="passRate" value-style="{color: '#409EFF'}" suffix="%" class="stat-item"
            size="mini"></el-statistic>
        </div>
      </div>

      <!-- 无成绩提示 -->
      <div class="empty-state" v-else-if="student">
        <el-empty description="暂无成绩数据"></el-empty>
      </div>

      <!-- 科目统计信息 -->
      <div class="subject-stats" v-if="student.scores && Object.keys(student.scores).length">
        <h3 class="section-title">
          <i class="el-icon-chart"></i> 科目统计信息
        </h3>
        <el-table :data="subjectStatsList" border stripe class="subject-stats-table" size="mini">
          <el-table-column prop="subject" label="科目" width="180" align="center"></el-table-column>
          <el-table-column prop="classAverage" label="班级平均分" width="120" align="center"></el-table-column>
          <el-table-column prop="classMax" label="班级最高分" width="120" align="center"></el-table-column>
          <el-table-column prop="classMin" label="班级最低分" width="120" align="center"></el-table-column>
          <el-table-column prop="classPassRate" label="班级及格率" width="120" align="center">
            <template slot-scope="scope">
              {{ scope.row.classPassRate }}%
            </template>
          </el-table-column>
          <el-table-column prop="rank" label="班级排名" width="100" align="center"></el-table-column>
        </el-table>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="warning" icon="el-icon-download" @click="handleExport" size="mini" v-if="student">
          导出详情
        </el-button>
      </div>
    </el-card>

    <!-- 无学生数据提示 -->
    <div class="empty-state" v-if="!student && !loading">
      <el-empty description="未找到对应学生数据"></el-empty>
    </div>
  </div>
</template>

<script>
// 导入学生数据和班级数据（实际项目中通常从API获取）
import classData from './classData'
import studentData from './studentData'

export default {
  name: 'StudentDetail',
  data() {
    return {
      loading: true,
      student: null,
      scoreList: [],
      subjectStatsList: [],
      isEditing: false,
      editForm: {}
    }
  },
  computed: {
    // 计算学生平均分
    averageScore() {
      if (!this.scoreList.length) return 0
      const total = this.scoreList.reduce((sum, item) => sum + item.score, 0)
      return total / this.scoreList.length
    },
    // 计算学生最高分
    maxScore() {
      if (!this.scoreList.length) return 0
      return Math.max(...this.scoreList.map(item => item.score))
    },
    // 计算学生最低分
    minScore() {
      if (!this.scoreList.length) return 0
      return Math.min(...this.scoreList.map(item => item.score))
    },
    // 计算学生及格率
    passRate() {
      if (!this.scoreList.length) return 0
      const passCount = this.scoreList.filter(item => item.score >= 60).length
      return Math.round((passCount / this.scoreList.length) * 100)
    }
  },
  async mounted() {
    try {
      // 获取路由参数中的学生ID
      const studentId = parseInt(this.$route.query.id)
      if (!studentId) {
        this.$message.error('学生ID不存在')
        this.loading = false
        return
      }

      // 加载学生数据和统计信息
      await this.fetchStudentData(studentId)
      await this.calculateSubjectStats()
    } catch (error) {
      this.$message.error(`加载失败: ${error.message}`)
      this.loading = false
    }
  },
  methods: {
    // 返回上一页
    backHandler() {
      this.$router.go(-1)
    },

    // 获取学生数据
    async fetchStudentData(id) {
      return new Promise(resolve => {
        setTimeout(() => {
          // 从本地数据中查找学生
          this.student = studentData.find(student => student.id === id)

          // 初始化编辑表单
          this.initializeEditForm()

          // 处理成绩数据
          if (this.student && this.student.scores) {
            this.scoreList = Object.entries(this.student.scores).map(([subject, score]) => ({
              subject,
              score,
              grade: this.getGrade(score)
            }))
          }

          this.loading = false
          resolve()
        }, 500)
      })
    },

    // 初始化编辑表单
    initializeEditForm() {
      if (this.student) {
        this.editForm = {
          name: this.student.name,
          age: this.student.age,
          gender: this.student.gender,
          major: this.student.major,
        }
      }
    },

    // 切换编辑模式
    toggleEditMode() {
      this.isEditing = !this.isEditing
      // 如果取消编辑，重置表单和成绩
      if (!this.isEditing) {
        this.initializeEditForm()
        this.resetScoreList()
      }
    },

    // 重置成绩列表（取消编辑时）
    resetScoreList() {
      if (this.student && this.student.scores) {
        this.scoreList = Object.entries(this.student.scores).map(([subject, score]) => ({
          subject,
          score,
          grade: this.getGrade(score)
        }))
      }
    },

    // 保存编辑内容
    saveEdit() {
      // 简单验证
      if (!this.editForm.name || !this.editForm.age) {
        this.$message.error('姓名、年龄为必填项')
        return
      }

      // 更新学生基本信息
      Object.assign(this.student, this.editForm)

      // 更新成绩信息并同步等级
      this.scoreList.forEach(item => {
        this.student.scores[item.subject] = item.score
        item.grade = this.getGrade(item.score)
      })

      // 重新计算统计信息
      this.calculateSubjectStats()

      // 退出编辑模式
      this.isEditing = false

      // 提示保存成功
      this.$message.success('信息保存成功')

      // 实际项目中这里应该调用API保存数据
      console.log('保存学生信息:', this.student)
    },

    // 根据分数获取等级
    getGrade(score) {
      if (score >= 90) return '优秀'
      if (score >= 80) return '良好'
      if (score >= 70) return '中等'
      if (score >= 60) return '及格'
      return '不及格'
    },

    // 计算各科目班级统计信息
    calculateSubjectStats() {
      if (!this.scoreList.length || !classData.length) {
        this.subjectStatsList = []
        return
      }

      // 计算每个科目的统计数据
      this.subjectStatsList = this.scoreList.map(({ subject }) => {
        // 收集班级所有学生该科目的有效成绩
        const allScores = classData
          .filter(student => student.scores?.[subject] !== undefined)
          .map(student => student.scores[subject])

        // 基础统计计算
        const totalScore = allScores.reduce((sum, score) => sum + score, 0)
        const passCount = allScores.filter(score => score >= 60).length
        const currentScore = this.student.scores[subject]

        return {
          subject,
          classAverage: allScores.length ? (totalScore / allScores.length).toFixed(1) : 0,
          classMax: allScores.length ? Math.max(...allScores) : 0,
          classMin: allScores.length ? Math.min(...allScores) : 0,
          classPassRate: allScores.length ? Math.round((passCount / allScores.length) * 100) : 0,
          rank: allScores.filter(score => score > currentScore).length + 1
        }
      })
    },

    // 导出学生详情
    handleExport() {
      if (!this.student) return
      this.$message.success(`正在导出${this.student.name}的详情信息`)
      // 实际项目中可使用 xlsx 等库实现 Excel 导出
    },

    // 处理成绩输入（确保分数在0-100之间）
    handleScoreInput(index) {
      const score = this.scoreList[index].score
      if (score < 0) this.scoreList[index].score = 0
      if (score > 100) this.scoreList[index].score = 100
    }
  }
}
</script>

<style scoped>
.student-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.back-btn {
  margin-right: 15px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.student-card {
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.empty-state {
  padding: 50px 0;
  text-align: center;
}

.student-info {
  padding: 20px;
}

.section-title {
  font-size: 16px;
  color: #1f2d3d;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e5e6eb;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.section-title i {
  margin-right: 8px;
  color: #409eff;
}
</style>